<?php

namespace App\Http\Controllers\Api;
use App\Blocks\User;
use App\Http\Controllers\Controller;
use App\Http\Requests\bindMobile;
use App\Http\Requests\UserAddress;
use App\Libs\ResponseMessage;
use App\Models\SignInLogs;
use App\Models\Users;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class UserController extends Controller {

    public function weixinCallback(Request $request){
        $app = Factory::officialAccount(\Config::get('wechat.official_account.default'));
        $oauth = $app->oauth;
        $user = $oauth->user();

        $userBlock = new User();
        $userInfo = $userBlock->getUserByWxOpenid($user->getId());
        if(!$userInfo){
            $wxuser = $user->getOriginal();

            $saveUserData = [
                'wechat_id'         => 0,
                'subscribe_time'    => isset($wxuser['subscribe_time'])?date('Y-m-d H:i:s', $wxuser['subscribe_time']):null,
                'openid'            => $wxuser['openid'],
                'nickname'          => isset($wxuser['nickname'])?$wxuser['nickname']:null,
                'city'              => isset($wxuser['city'])?$wxuser['city']:null,
                'province'          => isset($wxuser['province'])?$wxuser['province']:null,
                'country'           => isset($wxuser['country'])?$wxuser['country']:null,
                'sex'               => isset($wxuser['sex'])?$wxuser['sex']:null,
                'headimgurl'        => isset($wxuser['headimgurl'])?$wxuser['headimgurl']:null,
                'subscribe'         => isset($wxuser['subscribe'])?$wxuser['subscribe']:0,
                'create_time'       => date('Y-m-d H:i:s', time()),
            ];
            $userId = $userBlock->saveUserByWeixin($saveUserData);

            if($userId){
                $userInfo = [
                    'openid' => $saveUserData['openid'],
                    'wx_openid' => $saveUserData['openid'],
                    'headimgurl' => $saveUserData['headimgurl'],
                    'nick_name' => $saveUserData['nickname'],
                    'mobile' => null,
                    'id' => $userId,
                    'member' => 0,
                    'balance' => 0
                ];

                $userInfo = (object)$userInfo;
            }
        }

        if(isset($userInfo->id)){
            if(isset($userInfo->create_time)){
                unset($userInfo->create_time);
            }

            $sessionKey = md5($userInfo->wx_openid);
            \Cache::put($sessionKey, $userInfo, \Config::get('session.lifetime'));

            $userInfo->token = $sessionKey;

            if($request->has('redirect')){
                $redirect = $request->get('redirect');
                $url = env('WEB_URL').'/index';
                if('eat-every-day' === $redirect){
                    $url = env('WEB_URL').'/activity/eat-every-day';
                }

                return redirect($url)->withCookie(\Config::get('session.guoxiaojian_cookie'), $sessionKey, \Config::get('session.lifetime'));
            }
            return response()->json($userInfo);
        }else{
            return response()->json(['error' => '登录失败']);
        }
    }


    public function miniAuthLogin(Request $request){
        $app = Factory::miniProgram(\Config::get('wechat.mini_program.default'));
        $session = $app->auth->session($request->get('code'));

        $token = \Cookie::get(\Config::get('session.guoxiaojian_cookie'));
        $userInfo = \Cache::get($token);

        return response()->json(ResponseMessage::getInstance()->success(['session' => $session, 'userInfo' => $userInfo])->response());
    }
    public function miniLogin(Request $request){
        $wxuser = $request->all();
        $userBlock = new User();
        $userInfo = $userBlock->getUserByWxOpenid($wxuser['openid']);
        if(!$userInfo){

            $saveUserData = [
                'wechat_id'         => 0,
                'openid'            => isset($wxuser['openid'])?$wxuser['openid']:null,
                'nickname'          => isset($wxuser['nickName'])?$wxuser['nickName']:null,
                'city'              => isset($wxuser['city'])?$wxuser['city']:null,
                'province'          => isset($wxuser['province'])?$wxuser['province']:null,
                'country'           => isset($wxuser['country'])?$wxuser['country']:null,
                'sex'               => isset($wxuser['gender'])?$wxuser['gender']:null,
                'headimgurl'        => isset($wxuser['avatarUrl'])?$wxuser['avatarUrl']:null,
                'create_time'       => date('Y-m-d H:i:s', time()),
            ];
            $userId = $userBlock->saveUserByWeixin($saveUserData);

            if($userId){
                $userInfo = [
                    'openid' => $saveUserData['openid'],
                    'wx_openid' => $saveUserData['openid'],
                    'headimgurl' => $saveUserData['headimgurl'],
                    'nick_name' => $saveUserData['nickname'],
                    'mobile' => null,
                    'id' => $userId,
                    'member' => 0,
                    'balance' => 0
                ];

                $userInfo = (object)$userInfo;
            }
        }

        if(isset($userInfo->id)){
            if(isset($userInfo->create_time)){
                unset($userInfo->create_time);
            }

            $sessionKey = md5($userInfo->wx_openid);
            \Cache::put($sessionKey, $userInfo, \Config::get('session.lifetime'));

            $userInfo->token = $sessionKey;

            return response()->json(ResponseMessage::getInstance()->success($userInfo)->response())->withCookie(\Config::get('session.guoxiaojian_cookie'), $sessionKey, \Config::get('session.lifetime'));
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }
    }

    public function getUserAddress(){
        global $g_uid;

        $userBlock = new User();

        $address = $userBlock->getUserAddress($g_uid);
        return response()->json(ResponseMessage::getInstance()->success($address)->response());
    }

    public function getUserAddressInfo($id){
        global $g_uid;

        $userBlock = new User();

        $address = $userBlock->getUserAddressInfo($g_uid, $id);
        return response()->json(ResponseMessage::getInstance()->success($address)->response());
    }

    public function addUserAddress(UserAddress $request){
        global $g_uid;
        $name = $request->get('name');
        $mobile = $request->get('mobile');
        $province = $request->get('province');
        $city = $request->get('city');
        $district = $request->get('district');
        $address = $request->get('address');
        $useing = $request->get('useing', 0);

        $data = [
            'u_id' => $g_uid,
            'name' => $name,
            'mobile' => $mobile,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'address' => $address,
            'useing' => $useing,
            'created_at' => date('Y-m-d H:i:s', time())
        ];


        if(isset($data['useing']) && $data['useing'] == 1){
            \App\Models\UserAddress::where('u_id', $g_uid)->update(['useing' => 0]);
        }

        $userAddressModel = new \App\Models\UserAddress();
        if($userAddressModel->saveData($data)){
            return response()->json(ResponseMessage::getInstance()->success()->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }
    }

    public function updateUserAddress(Request $request){
        global $g_uid;
        $id = $request->get('id');
        if(!$id){
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }

        $updateField = [
            'name',
            'mobile',
            'province',
            'city',
            'district',
            'address',
            'useing'
        ];

        $updateData = [];

        foreach ($updateField as $field){
            if($request->has($field)){
                $updateData[$field] = $request->get($field);
            }
        }

        if($request->has('del')){
            $updateData['deleted_at'] = date('Y-m-d H:i:s', time());
        }


        if(isset($updateData['useing']) && $updateData['useing'] == 1){
            \App\Models\UserAddress::where('u_id', $g_uid)->update(['useing' => 0]);
        }

        if(\App\Models\UserAddress::where('id', $id)->where('u_id', $g_uid)->update($updateData)){
            return response()->json(ResponseMessage::getInstance()->success()->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }
    }

    public function my(){
        global $g_uid;
        $userBlock = new User();
        $user = $userBlock->getUserByUid($g_uid);
        return response()->json(ResponseMessage::getInstance()->success($user)->response());
    }

    public function bindMobile(bindMobile $request){
        global $g_uid;
        $mobile = $request->get('mobile');
        $code = $request->get('code');

        $cacheCode = \Cache::get($mobile);
        if($cacheCode != $code){
            return response()->json(ResponseMessage::getInstance()->failed('VERIFICATION_CODE_ERROR')->response());
        }

        if(Users::where('id', $g_uid)->update(['mobile' => $mobile]) === false){
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->success()->response());
        }
    }

    public function signIn(){
        global $g_uid;

        $signBlock = new User();

        $addIntegral = $signBlock->signIn($g_uid);
        if($addIntegral){
            return response()->json(ResponseMessage::getInstance()->success($addIntegral)->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }

    }
}